Skip to main content
ICT
Lesson A10 - The String Class
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

D. The null Value page 6 of 17

  1. In most programs, objects are created and objects are destroyed, depending on the data and on what is being computed. A reference variable sometimes does and sometimes does not refer to an object. You may need a way to erase the reference inside a variable without creating a new reference. You do this by assigning null to the variable.

  2. The value null is a special value that means "no object." A reference variable is set to null when it is not referring to any object.

    String a =                // 1. an object is created;
       new String("stringy"); // variable a refers to it
    String b = null;          // 2. variable b refers to no
                              // object.
    String c =                // 3. an object is created
       new String("");        // (containing no characters)
                              // variable c refers to it
    if (a != null)            // 4. statement true, so
    System.out.println(a);    // the println(a) executes.

    if (b != null)            // 5. statement false, so the
    System.out.println(b);    // println(b) is skipped.

    if (c != null)            // 6. statement true, so the
    System.out.println(c);    // println(c) executes (but
                              // it has no characters to
                              // print).

    Run Output:

    stringy

  3. Variables a and c are initialized to object references. Variable b is initialized to null. Note that variable c is initialized to a reference to a String object containing no characters. Therefore println(c) executes, but it has no characters to print. Having no characters is different from the value being null.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.